/* 路由 */

import {
  Dialog
} from 'vant'
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
Vue.use(VueRouter)


// 解决路由跳转报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}


const routes = [{
  path: '/',
  component: () => import('../views/layout'),
  children: [{
    path: '',
    name: 'home',
    component: () => import('../views/home'),
    meta: {
      requiresAuth: false
    }
  }, {
    path: 'qa',
    name: 'qa',
    component: () => import('../views/qa/index.vue'),
    meta: {
      requiresAuth: true
    }
  }, {
    path: 'video',
    name: 'video',
    component: () => import('../views/video'),
    meta: {
      requiresAuth: false
    }
  }, {
    path: 'my',
    name: 'my',
    component: () => import('../views/my'),
    meta: {
      requiresAuth: false
    }
  }]
}, {
  path: '/login',
  name: 'login',
  component: () => import('../views/login/'),
  meta: {
    requiresAuth: false
  }
}, {
  path: '/search',
  name: 'search',
  component: () => import('../views/search'),
  meta: {
    requiresAuth: false
  }
}, {
  path: '/articles/:articleId',
  name: 'articles',
  component: () => import('../views/article/'),
  //动态路由参数映射到组件的 props
  props: true,
  meta: {
    requiresAuth: false
  }
}, {
  path: '/user/profile',
  name: "userProfile",
  component: () => import('../views/user-profile/index.vue'),
  meta: {
    requiresAuth: true
  }
}, {
  path: '/user/chat',
  name: 'UserChat',
  component: () => import('../views/user-chat/index.vue'),
  meta: {
    requiresAuth: true
  }
}, {
  path: '/tree',
  name: 'Tree',
  component: () => import('../views/tree/index.vue'),
  meta: {
    requiresAuth: false
  }
}, {
  path: '*',
  component: () => import('../views/404')
}]

const router = new VueRouter({
  routes
})

// 限制访问
router.beforeEach((to, from, next) => {
  if (store.state.userInfo)
    return next()
  if (to.meta.requiresAuth) {
    Dialog.confirm({
      title: '访问提示',
      message: "此页面需要登录才能访问"
    }).then(() => {
      router.push({
        name: 'login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      })
      next()
    }).catch(() => {
      next(false) //取消访问
    })
  } else {
    next()
  }
})

export default router